package cn.itcast.login;

import cn.itcast.base.BaseContorller;
import cn.itcast.domain.Module;
import cn.itcast.domain.User;
import cn.itcast.service.module.ModuleService;
import cn.itcast.service.user.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class LoginController extends BaseContorller {
    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;
    /*@RequestMapping(value = "/login.do", name = "用户登录")
    public String login(String email,String password) {
        if (UtilFuns.isEmpty(email) || UtilFuns.isEmpty(password)) {
            // 登录失败--账号密码为空
            return "forward:login.jsp";
        }
        *//*根据用户做登录*//*
        User user = userService.findByUserName(email);
        System.out.println(user);
        if (user == null ||!user.getPassword().equals(password)) {
            // 登录失败--账号密码不匹配
            request.setAttribute("error","账号或密码错误...");
            return "forward:login.jsp";
        }
        //3 登录成功
        session.setAttribute("loginUser",user);
        *//*根据用户展示不同的菜单模板*//*
       List<Module> modulelist= moduleService.findMenus(user);
        session.setAttribute("modules",modulelist);
        return "home/main";

    }*/
    @RequestMapping(value = "/login.do",name ="用户登录")
    public String login(String email,String password) {
        try {
            /*shior的认证  获取subject对象 */
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(email,password);
            /*认证的入口 回去找安全管理器AuthRealm 做认证*/
            subject.login(usernamePasswordToken);
            //登录认证成功的用户放入session
            User user = (User)subject.getPrincipal();
            session.setAttribute("loginUser",user);
                //*根据用户展示不同的菜单模板
            List<Module> modulelist= moduleService.findMenus(user);
            session.setAttribute("modules",modulelist);
        }catch (Exception e){
            /*   登录失败--账号密码不匹配  会抛出异常被捕获*/
            request.setAttribute("error","账号或密码错误...");
            return "forward:login.jsp";
        }
        return "home/main";
    }
    //退出
    @RequestMapping(value = "/logout", name = "用户登出")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home() {

        return "home/home";
    }
}
